package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.CustomEventHandler;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.TaskCreatedPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.exception.EventCallSuspendException;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowTaskEntrustService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.common.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.common.api.delegate.event.FlowableEvent;
import org.flowable.engine.common.api.delegate.event.FlowableEventType;
import org.flowable.engine.common.impl.event.FlowableEntityEventImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * 任务创建事件处理器
 *
 * @author cheng.huaxing
 * @date 2019-03-19
 */
@Slf4j
@Component
public class TaskCreateHandler implements CustomEventHandler {

    @Lazy
    @Autowired(required = false)
    private List<TaskCreatedPostProcessor> taskCreatedPostProcessors = new ArrayList<>();

    @Lazy
    @Autowired(required = false)
    private FlowTaskEntrustService flowTaskEntrustService;

    @Override
    public FlowableEventType getEventType() {
        return FlowableEngineEventType.TASK_CREATED;
    }


    @Override
    public void handle(FlowableEvent event) throws Exception {
        if (!FlowableEntityEventImpl.class.isAssignableFrom(event.getClass())) {
            return;
        }
        FlowableEntityEventImpl entityEvent = (FlowableEntityEventImpl) event;
        TaskEntity taskEntity = (TaskEntity) entityEvent.getEntity();
        //在这里做
        if (Objects.isNull(taskEntity.getExecutionId()) && Objects.nonNull(taskEntity.getParentTaskId())) {
            //将父任务中的变量传给子任务的本地变量里，因为未指定executionId的情况下，无法从流程中获取流程变量
            TaskEntity parentTask = CommandContextUtil.getTaskService().getTask(taskEntity.getParentTaskId());
            if (Objects.nonNull(parentTask)) {
                taskEntity.setVariablesLocal(parentTask.getVariables());
            }
            //CommandContextUtil.getExecutionEntityManager().findById(taskEntity.getProcessInstanceId());
        }
        executePostProcessors(taskEntity);

        // 处理Task的委托
        flowTaskEntrustService.entrustTask(taskEntity);
    }

    private void executePostProcessors(TaskEntity taskEntity) throws Exception {
        for (TaskCreatedPostProcessor processor : taskCreatedPostProcessors) {
            try {
                long startTime = System.currentTimeMillis();
                processor.process(taskEntity);
                log.info("finish TASK_CREATED processor = {}, timeCost = {}",processor.getClass().getSimpleName(),System.currentTimeMillis()-startTime);
            } catch (EventCallSuspendException e) {
                log.warn(e.getMessage());
                throw e;
            } catch (Exception e) {
                log.warn("任务创建时，执行自定义逻辑发生异常：{}", ExceptionUtil.stacktraceToString(e));
                throw e;
            }
        }
    }


}
